/**
 * 航点管理相关功能 Composable
 * 包含航点的增删改查、记录管理等功能
 */
import { ref, computed, getCurrentInstance } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import { toLatLng, addDrone, addGround } from "../assets/cesiumFunction/Map"
import { uavLayerName, groundLayerName } from "../assets/cesiumFunction/LayerName"
import { useMapCore } from './useMapCore'
import { ElMessage } from 'element-plus'

// 全局变量，用于存储实体
let uavEntity = {}
let groundEntity = {}


export function useWaypointManagement() {
  // 获取当前实例以访问 $bus
  const instance = getCurrentInstance()
  const $bus = instance?.appContext.config.globalProperties.$bus
  
  // 获取地图核心功能
  const { GodViewer, tracker } = useMapCore()
  // 响应式数据
  const recordList = ref([])
  const currentIndex = ref(0)
  const currentRecord = ref({
    'uavId': null,
    "is_risky": 0,
    "point_index": 0,
    "point_name": "0",
    "point_type": 0,
    "point_gimbal_pitch_angle": 0.0,
    "point_coordinate": {
      longitude: 0,
      latitude: 0,
      altitude: 0,
    },
    "point_actions": [
      {
        "action_type": 40,
        "point_ground": {
          longitude: 0,
          latitude: 0,
          altitude: 0,
        },
        "groundId": null,
      }
    ],
  })
  const oldSpeedOption = ref(0)
  const oldHeightOption = ref(0)

  // 计算属性
  const currentIndexName = computed(() => {
    if (!currentRecord.value.positionName) {
      currentRecord.value.positionName = "航点" + currentIndex.value.toString()
    }
    return currentRecord.value.positionName
  })

  /**
   * 绘制无人机航点
   */
  const drawDrone = (mode) => {
    if (!tracker.value) {
      console.error('tracker 未初始化，请确保地图已正确加载')
      return
    }
    
    tracker.value.trackPoint(
      async (position) => {
        const LatLon = toLatLng(position)
        LatLon['altitude'] = 100
        
        switch (mode) {
          case 0:
            addNewWaypoint(LatLon, position)
            break
          case 1:
            editExistingWaypoint(LatLon)
            break
          default:
            break
        }
      }
    )
  }

  /**
   * 添加新航点
   */
  const addNewWaypoint = (LatLon, position) => {
    const uavId = uuidv4()
    const groundId = uuidv4()
    
    ElMessage.success('航点有效，操作成功！')
    
    // 添加到记录列表
    recordList.value.push({
      'uavId': uavId,
      "is_risky": 0,
      "point_index": recordList.value.length,
      "point_name": currentIndexName.value,
      "point_type": 0,
      "point_gimbal_pitch_angle": 0.0,
      "point_coordinate": LatLon,
      "point_turn_type": 2,
      "point_heading_type": 2,
      "point_fly_speed": 10,
      "point_fly_height": LatLon['altitude'],
      "point_actions": [
        {
          "action_type": 40,
          "point_ground": {
            longitude: LatLon.longitude,
            latitude: LatLon.latitude,
            altitude: 0,
          },
          "groundId": groundId
        }
      ],
    })

    currentIndex.value = recordList.value.length
    currentRecord.value = recordList.value[currentIndex.value - 1]

    // 使用内部 $bus 实例发送事件
      $bus.$emit('addRouteSeqPoint', {
        positionIndex: currentIndex.value,
        position: {
          longitude: LatLon.longitude,
          latitude: LatLon.latitude
        }
      })

    // 添加地面点
    const groundPOi = addGround(
      GodViewer.value,
      uavId, groundLayerName, position, `地面点`
    )
    groundEntity[groundId] = groundPOi

    // 添加空中点
    const position3D = Cesium.Cartesian3.fromDegrees(LatLon.longitude, LatLon.latitude, LatLon.altitude)
    const uavPOi = addDrone(
      GodViewer.value,
      uavId, uavLayerName, position3D, `空中点${recordList.value.length}`
    )
    uavEntity[uavId] = uavPOi
  }

  /**
   * 编辑现有航点
   */
  const editExistingWaypoint = (LatLon) => {
    if (LatLon != null) {
      currentRecord.value.point_coordinate = LatLon
    }
    
    const uavId = currentRecord.value.uavId
    GodViewer.value.entities.remove(uavEntity[uavId])
    
    const position3D = Cesium.Cartesian3.fromDegrees(LatLon.longitude, LatLon.latitude, LatLon.altitude)
    const uavPOi = addDrone(
      GodViewer.value,
      uavId, uavLayerName, position3D, `空中点${currentIndex.value}`
    )
    uavEntity[uavId] = uavPOi
  }

  /**
   * 添加新记录
   */
  const addRecord = () => {
    drawDrone(0)
  }

  /**
   * 编辑记录
   */
  const editRecord = () => {
    drawDrone(1)
  }

  /**
   * 编辑地面记录
   */
  const editGroundRecord = () => {
    const oldUavId = currentRecord.value.uavId
    const uavPosition = Cesium.Cartesian3.fromDegrees(
      currentRecord.value.point_coordinate.longitude,
      currentRecord.value.point_coordinate.latitude,
      currentRecord.value.point_fly_height
    )
    $bus.$emit("drawGround", { 
      'name': 1, 
      'oldPosition': uavPosition, 
      'oldUavId': oldUavId 
    })
  }

  /**
   * 删除记录
   */
  const delRecord = () => {
    if (currentIndex.value == 0) return
    
    const uavId = currentRecord.value.uavId
    GodViewer.value.entities.remove(uavEntity[uavId])
    delete uavEntity[uavId]
    
    // 使用内部 $bus 实例发送事件
      $bus.$emit('delRouteSeqPoint', currentIndex.value - 1)
    recordList.value.splice(currentIndex.value - 1, 1)
    
    const groundId = currentRecord.value.point_actions[0].groundId
    GodViewer.value.entities.remove(groundEntity[groundId])
    delete groundEntity[groundId]

    if (recordList.value.length == 0) {
      return
    } else {
      if (currentIndex.value == 1) {
        currentIndex.value = 1
        currentRecord.value = recordList.value[currentIndex.value - 1]
        return
      } else {
        lastRecord()
      }
    }
    updateUavText()
  }

  /**
   * 上一条记录
   */
  const lastRecord = () => {
    if (currentIndex.value > 0) {
      currentIndex.value -= 1
      currentRecord.value = recordList.value[currentIndex.value - 1]
    }
  }

  /**
   * 下一条记录
   */
  const nextRecord = () => {
    if (currentIndex.value != recordList.value.length) {
      currentIndex.value += 1
      currentRecord.value = recordList.value[currentIndex.value - 1]
    }
  }

  /**
   * 添加动作
   */
  const addAction = () => {
    currentRecord.value.point_actions.push({
      action_type: null,
      action_param_value: null,
    })
  }

  /**
   * 删除动作
   */
  const delAction = (index) => {
    currentRecord.value.point_actions.splice(index, 1)
  }

  /**
   * 更新空中点名称
   */
  const updateUavText = () => {
    recordList.value.map((item, index) => {
      const model = uavEntity[item.uavId]
      model.label.text = `空中点${index + 1}`
    })
  }

  /**
   * 根据PID删除记录
   */
  const delRecordByPid = (pId) => {
    for (let recordIndex in recordList.value) {
      if (recordList.value[recordIndex].pId == pId) {
        const uavId = recordList.value[recordIndex].uavId
        delete uavEntity[uavId]
        recordList.value.splice(recordIndex, 1)
        // 使用内部 $bus 实例发送事件
        $bus.$emit('delRouteSeqPoint', recordIndex)
        updateUavText()
      }
    }
  }

  /**
   * 初始化航点实体（从外部数据加载时使用）
   * 为 recordList 中的每个航点创建对应的 Cesium 实体
   */
  const initWaypointEntities = () => {
    if (!GodViewer.value) {
      console.error('GodViewer 未初始化')
      return
    }
    
    recordList.value.forEach((record, index) => {
      // 确保每个记录都有 uavId
      if (!record.uavId) {
        record.uavId = uuidv4()
      }
      
      const uavId = record.uavId
      
      // 如果实体已存在，跳过
      if (uavEntity[uavId]) {
        return
      }
      
      // 创建空中点实体
      const position3D = Cesium.Cartesian3.fromDegrees(
        Number(record.point_coordinate.longitude),
        Number(record.point_coordinate.latitude),
        Number(record.point_fly_height || record.point_coordinate.altitude || 100)
      )
      
      const uavPOi = addDrone(
        GodViewer.value,
        uavId,
        uavLayerName,
        position3D,
        `空中点${index + 1}`
      )
      uavEntity[uavId] = uavPOi
      
      // 如果有地面点，也创建地面点实体
      if (record.point_actions && record.point_actions.length > 0) {
        const action40 = record.point_actions.find(action => action.action_type === 40)
        if (action40 && action40.point_ground) {
          if (!action40.groundId) {
            action40.groundId = uuidv4()
          }
          
          const groundPosition = Cesium.Cartesian3.fromDegrees(
            Number(action40.point_ground.longitude),
            Number(action40.point_ground.latitude),
            Number(action40.point_ground.altitude || 0)
          )
          
          const groundPOi = addGround(
            GodViewer.value,
            uavId,
            groundLayerName,
            groundPosition,
            `地面点`
          )
          groundEntity[action40.groundId] = groundPOi
        }
      }
    })
  }

  /**
   * 更新航点高度
   * @param {string} uavId - 航点ID
   * @param {number} height - 新的高度值
   */
  const updateWaypointHeight = (uavId, height) => {
    if (!uavId || !uavEntity[uavId]) {
      console.warn('无法更新航点高度：uavId 无效或实体不存在', { uavId, uavEntity })
      return
    }
    
    const entity = uavEntity[uavId]
    const currentPosition = entity.position.getValue()
    
    // 将当前位置转换为经纬度
    const cartographic = Cesium.Cartographic.fromCartesian(currentPosition)
    const longitude = Cesium.Math.toDegrees(cartographic.longitude)
    const latitude = Cesium.Math.toDegrees(cartographic.latitude)
    
    // 使用新的高度创建新位置
    const newPosition = Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
    
    // 更新实体位置（使用 ConstantProperty 确保正确更新）
    entity.position = new Cesium.ConstantProperty(newPosition)
  }

  return {
    // 响应式数据
    recordList,
    currentIndex,
    currentRecord,
    oldSpeedOption,
    oldHeightOption,
    
    // 计算属性
    currentIndexName,
    
    // 方法
    drawDrone,
    addNewWaypoint,
    editExistingWaypoint,
    addRecord,
    editRecord,
    editGroundRecord,
    delRecord,
    lastRecord,
    nextRecord,
    addAction,
    delAction,
    updateUavText,
    delRecordByPid,
    updateWaypointHeight,
    initWaypointEntities
  }
}